<template>
    <div class="dynamicMessage">
        <cardComponent class="staticMessage-container" pageTitle="发送短信">
            <template slot="cardBody">
                <el-form
                    :inline="true"
                    :model="formData"
                    class="typeChang menu-setting demo-form-inline"
                    label-width="100px"
                    size="small"
                >
                    <!--<el-form-item label="模板编码:">-->
                    <!--<el-input v-model="formData.id"></el-input>-->
                    <!--</el-form-item>-->
                    <el-form-item label="模板类型:">
                        <el-select v-model="formData.tempType" @change="hanlesearch" clearable>
                            <el-option label="动态模板类型" value="D"></el-option>
                            <el-option label="静态模板类型" value="S"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="sendMess demo-form-inline">
                    <el-form
                        ref="formDataMessage"
                        class="menu-setting"
                        :model="formDataMessage"
                        :rules="formRules"
                        label-width="100px"
                        size="small"
                    >
                        <el-form-item label="短信模板:">
                            <el-select
                                v-model="formDataMessage.id"
                                filterable
                                clearable
                                @change="changeTempId"
                            >
                                <el-option
                                    v-for="item in tempList"
                                    :key="item.id"
                                    :label="item.tempName"
                                    :value="item.id"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="手机号码:" prop="mobilePhone">
                            <el-input v-model="formDataMessage.mobilePhone"></el-input>
                        </el-form-item>
                        <el-form-item label="短信内容:" prop="tempContent">
                            <el-input
                                type="textarea"
                                class="textareaStyle"
                                :autosize="{minRows:4,maxRows:5}"
                                v-model="formDataMessage.tempContent"
                            ></el-input>
                        </el-form-item>
                        <div class="dynamicButton">
                            <el-button
                                type="primary"
                                size="small"
                                @click="hanleSendMessage"
                                :loading="sendLoading"
                                class="submitBtn"
                            >发 送</el-button>
                        </div>
                    </el-form>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import { dealTempContent } from '@/utils/Common';
import { getTokenHsbankNo } from '@/utils/auth';
export default {
    components: {
        cardComponent,
    },
    name: 'dynamicMessage',
    data() {
        return {
            formData: {
                id: '',
                tempType: '',
            },
            tempName: '', // 默认模板名称 ->路由参数接收
            tempContent: '', // 默认模板内容 ->路由参数接收
            fromPage: '',
            newArrType: [],
            // 搜索loading
            sendLoading: false,
            formDataMessage: {
                id: '',
                mobilePhone: '',
                tempContent: '',
            },
            formRules: {
                id: [
                    { required: true, message: '请选择短信模板', trigger: 'change' },
                ],
                mobilePhone: [
                    { required: true, message: '请输入用户手机号', trigger: 'blur' },
                ],
                tempContent: [
                    { required: true, message: '请输入短信内容', trigger: 'blur' },
                    { max: 300, message: '字符最大长度为300', trigger: 'blur' },
                ],
            },
            tempList: [],
        };
    },
    created() {
        // console.log(this.$route.query.tempName, 'this.$route.query')
        this.getInitData();
        this.getTempList();
    },
    computed: mapState({
        3004: state => state.common.cardInfo_3004, // 默认卡信息
        3001: state => state.common.cardAccountInfo_3001, // 卡账户信息
        3002: state => state.common.customerInfo_3002, // 客户信息
        3005: state => state.common.CardBill_3005,
        defaultParams: state => state.common.defaultParams, // 接口默认参数
    }),
    // activated() {
    //     this.getInitData();
    //     this.getTempList();
    // },
    methods: {
        getInitData() {
            console.log(this['3005'], '300530053005300530053005');
            const routeParams = this.$route.params;
            this.tempName = routeParams.tempName ? routeParams.tempName : '';
            this.tempContent = routeParams.tempContent;

            console.log("传入短信内容：", routeParams);
            this.formDataMessage.mobilePhone = this[3002].MOBILEPHONE;
            let card = this[3004].CARDNO.trim();
            this[3004].CARD4END = card.substring(12, 16);
        },
        getTempList() {
            this.$post.Template.searchList({}).then((res) => {
                if (res.data.success) {
                    this.tempList = res.data.content;
                    if (this.tempName) {
                        if (this.tempContent !== '' && this.tempContent != undefined) {
                            this.formDataMessage.tempContent = this.tempContent;
                        } else {
                            res.data.content.some((item) => {
                                if (item.tempName === this.tempName) {
                                    this.formDataMessage.id = item.id;
                                    //this.formDataMessage.tempContent = item.tempContent;
                                    this.changeTempId(item.id);
                                }
                            });
                        }
                    } else {
                        if (this.tempContent !== '') {
                            this.formDataMessage.tempContent = this.tempContent;
                        }
                    }
                    //this.formDataMessage.tempContent = this.tempContent;
                    this.newArrType = this.tempList;
                }
            });
        },
        // 切换短信模板
        async changeTempId(val) {
            let str = '';
            this.tempList.forEach((item) => {
                if (val === item.id) {
                    str = item.tempContent;
                }
            });
            console.log(str, ' console.log(str);');
            this.formDataMessage.tempContent = await dealTempContent(str, this);


        },
        hanlesearch(val) {
            if (!val) {
                this.getTempList();
                return;
            }
            const arr = [];
            if (this.formData.id) {
                this.newArrType.forEach((item) => {
                    if (this.formData.id === item.id) {
                        arr.push(item);
                    }
                });
            } else if (val) {
                this.newArrType.forEach((item) => {
                    if (val === item.tempType) {
                        arr.push(item);
                    }
                });
            }
            this.tempList = arr;
            this.formDataMessage.id = '';
            this.formDataMessage.tempContent = '';
        },
        hanleSendMessage() {
            this.$refs.formDataMessage.validate((valid) => {
                if (valid) {
                    this.sendLoading = true;
                    console.log("cardIds:" + this.optionCardNum);
                    let msgcontent = "尊敬的客户，您当前选择发送的卡号为" + this.optionCardNum;
                    console.log("msgcontent:", msgcontent);
                    const appBody = {
                        IntfCd: '101002033032',//交易吗（系统编号+服务吗）
                        SysId: '10100203',//系统编号
                        TrsCd: '3032',//服务代码
                        BrNo: '32010101',//机构号
                        ImmedFlg: '1',//实时标志，1-实时，0-非实时
                        BkgTm: '0',//预约时间，不预约发送，填0
                        MblNum: this.formDataMessage.mobilePhone,//this[3002].MOBILEPHONE,//手机号码
                        ShrtMsgCntnt: this.formDataMessage.tempContent, // 短信内容
                    };
                    this.defaultParams.sysHead.busiName = '短信发送';
                    const params = JSON.parse(JSON.stringify(this.defaultParams));
                    params.body.appHead.tranCode = '3032';
                    params.body.appBody = appBody;

                    // 跑 3032 交易
                    this.$post.common.esbtran(params).then((res) => {
                        this.sendLoading = false;
                        if (res.status === 200) { // 接口请求成功
                            const result = JSON.parse(res.data.jsonRes);
                            console.log(result, 'result -- 3032');
                            if (result.sysHead.rspCd === '000000') {
                                this.$alert(
                                    '短信发送成功',
                                    {
                                        center: true,
                                        customClass: 'success', type: 'success',
                                    },
                                );
                            } else {
                                const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspDesc}`;
                                this.$alert(errorMsg, result.sysHead.rspDesc, {
                                    customClass: 'error', type: 'error',
                                });
                            }
                        } else {
                            this.$message.error('请求失败');
                        }
                    });
                }
            });


        },
    },
};
</script>
<style lang="scss">
.dynamicMessage {
    .textareaStyle {
        width: 55%;
    }
}
</style>
<style scoped lang="scss">
.typeChang {
    padding-bottom: 0;
}
.dynamicButton {
    text-align: center;
}
.sendMess {
    padding-top: 0;
    .el-form--inline .el-form-item {
        display: block;
        text-align: left;
        margin-left: 14%;
    }
}
</style>
